//
//  HETeamSpecView.m
//  HealthElderly
//
//  Created by 吴欧 on 2021/1/21.
//  Copyright © 2021 honglutec. All rights reserved.
//

#import "HETeamSpecView.h"
#import "SepecConfig.h"
#import "CountView.h"
#import "UICollectionViewLeftAlignedLayout.h"
#import "KNPhotoBrowser.h"


static NSString * const HESepceCellID = @"HESepceCellID";
static NSString * const HEHeaderViewID = @"HEHeaderViewID";
static NSString * const HEFooterViewID = @"HEFooterViewID";
 

@interface HEAddAttriCollReusableView : UICollectionReusableView

@property (nonatomic, retain)UILabel *headerLab;

@property (nonatomic, assign)NSInteger section;

- (void)setAttriHeaderTitle:(NSString *)title;

- (void)setAttriFooterTitle:(NSString *)title;

@end

@implementation HEAddAttriCollReusableView

- (void)setAttriHeaderTitle:(NSString *)title{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 31)];
    view.tag = _section+10;
    [self addSubview:view];
    UIView *line = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, KScreenWidth - 10, 1)];
    line.backgroundColor = [UIColor grayColor];
    [view addSubview:line];
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(14, 1, KScreenWidth - 2*14, 30)];
    lab.textColor = [UIColor darkGrayColor];
    lab.font = DYFont(15);
    [view addSubview:lab];
    self.headerLab = lab;
    self.headerLab.text = title;
}

- (void)setAttriFooterTitle:(NSString *)title{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 35)];
    [self addSubview:view];
}


@end



@interface HESepecCell : UICollectionViewCell

@property (strong, nonatomic) UILabel *sepeclabel;
@property (nonatomic) SepecDetailModel *sepceModel;
@property (nonatomic) UIEdgeInsets contentInsets;

@end

@implementation HESepecCell

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame: frame]) {
        
        _sepeclabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 35)];
        _sepeclabel.textAlignment = NSTextAlignmentCenter;
        _sepeclabel.userInteractionEnabled = NO;
        _sepeclabel.textColor = [UIColor blackColor];
        _sepeclabel.font = DYFont(15);
        [self.contentView addSubview:_sepeclabel];
    }
    
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGRect bounds = self.contentView.bounds;
    CGFloat width = bounds.size.width - self.contentInsets.left - self.contentInsets.right;
    CGRect frame = CGRectMake(0, 0, width, self.sepceModel.contentSize.height);
    self.sepeclabel.frame = frame;
    self.sepeclabel.center = self.contentView.center;
}

@end

@interface HETeamSpecView ()<UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout, KNPhotoBrowserDelegate>

@property (strong, nonatomic) UICollectionView *collectionView;
@property (strong, nonatomic) NSMutableArray<NSString *> *tagsMutableArray;
@property (nonatomic, retain) SepecConfig *config;
@property (nonatomic, retain) UIView *contentView;
@property (nonatomic, retain) UIView *bgView;

@property (nonatomic, retain) UILabel *titleLb;
@property (nonatomic, retain) UILabel *spec_price;
@property (nonatomic, retain) UILabel *org_priceLb;
@property (nonatomic, retain) UILabel *specLab;


@property (nonatomic, assign) NSInteger num;
@property (nonatomic, assign) BOOL iscompelete;//判断是否选择完全
@property (nonatomic, strong) NSMutableArray *tempSelectArr;//临时存储选择中的模型
@property (nonatomic, strong) NSMutableArray *preflagarr; // 已选属性
@property (nonatomic, strong) UIImageView *goodsImageView;
@property (nonatomic, strong) UILabel *stockLb; // 库存

@property (nonatomic, strong) UIButton *actionBtn;
@property (nonatomic, strong) SepecDetailModel *selectModel;

@property (nonatomic, weak) KNPhotoBrowser *photoBrowser;
@property (nonatomic, strong) NSMutableArray *itemsArr;

@end

@implementation HETeamSpecView


+ (HETeamSpecView*)selectSpecViewWithdataArr:(NSArray <SepecModel *> *)dataArr {
    
    // 初始化
    HETeamSpecView *sepecView = [[HETeamSpecView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight) withDataArr:dataArr];
    
    // 取出未选择的
//    NSMutableArray *strs = [NSMutableArray array];
//    for (SepecModel *demodel in dataArr) {
//        [strs addObject:demodel.name_sepec];
//    }
//    sepecView.compeleteStr = [strs componentsJoinedByString:@","];

    [sepecView show];
    [[UIApplication sharedApplication].keyWindow addSubview:sepecView];
    return sepecView;
}

- (void)show {
    
    [_actionBtn setTitle:_comfireBtnTitle forState:UIControlStateNormal];
    _actionBtn.backgroundColor = CNavBgColor;
    
    self.hidden = self.contentView.hidden= self.bgView.hidden = NO;
    self.bgView.alpha = 0;
    [UIView animateWithDuration:0.5f animations:^{
        self.bgView.alpha = 1;
        self.contentView.frame = CGRectMake(0, KScreenHeight - self.config.height, KScreenWidth, self.config.height);
    }];
}

- (void)hiddenView{
    [UIView animateWithDuration:0.3f animations:^{
        self.contentView.frame = CGRectMake(0, KScreenHeight, KScreenWidth, self.config.height);
        self.bgView.alpha = 0;
    } completion:^(BOOL finished) {
        self.hidden = self.contentView.hidden=self.bgView.hidden = YES;
    }];
   }
- (void)setDataArr:(NSArray <SepecModel *> *)dataArr{
    _dataArr = dataArr;
    [self.collectionView reloadData];
}

- (instancetype)initWithFrame:(CGRect)frame withDataArr:(NSArray <SepecModel *> *)dataArr{
     [self setupConfig];
    self.dataArr = dataArr;
    if (self = [super initWithFrame:frame]) {
        UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight)];
        bgView.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0.3];
        [self addSubview:bgView];
        bgView.hidden = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenView)];
        [bgView addGestureRecognizer:tap];
        
        UIView *contentview = [[UIView alloc]initWithFrame:CGRectMake(0, KScreenHeight, KScreenWidth, _config.height)];
        contentview.backgroundColor = [UIColor whiteColor];
        bgView.hidden = YES;
        [self addSubview:contentview];
        
        [contentview addRoundedCorners:UIRectCornerTopLeft|UIRectCornerTopRight withRadii:CGSizeMake(20, 20)];
        
        self.contentView = contentview;
        self.bgView = bgView;
        [self otherViews];
        
        if (dataArr.count > 0) {
            [self addInitCollectView];
        }else {
            UIView *line = [[UIView alloc]initWithFrame:CGRectMake(5, 125, KScreenWidth - 10, 0.5)];
            line.backgroundColor = CSplitLineColor;
            [contentview addSubview:line];

            UIView *countbgview = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(line.frame), KScreenWidth, 49)];
            countbgview.backgroundColor = [UIColor whiteColor];
            [contentview addSubview:countbgview];

            UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(15, 5, KScreenWidth/2, 39)];
            lab.text = @"购买数量: ";
            lab.textColor = [UIColor blackColor];
            lab.font = DYFont(15);
            [countbgview addSubview:lab];

            CountView *view = [[CountView alloc]initWithFrame:CGRectMake(countbgview.zx_width - 155, 19/2, 140, 30)];
            view.count = 1;
            view.goodstock = 1000000;//可选择的最大销量
            view.CountBlock = ^(NSInteger count){
             self.num = count;
            };
            [countbgview addSubview:view];
        }
        
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(15, self.contentView.zx_height - AUTOY(_config.bottomBarHeight), KScreenWidth - 30, AUTOY(40));
        btn.layer.masksToBounds = YES;
        btn.layer.cornerRadius = AUTOY(40)/ 2.0;
        btn.backgroundColor = CNavBgColor;
        [self.contentView addSubview:btn];
        [btn setTitle:_comfireBtnTitle forState:UIControlStateNormal];
        btn.titleLabel.font = DYBlodFont(15);
        [btn setTitleColor:[UIColor whiteColor] forState:0];
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        _actionBtn = btn;
    }
    return self;
}
#pragma mark - 头部视图 需要展示数据 如销量之类的 可在这里添加
- (void)otherViews{
    
    _goodsImageView = [[UIImageView alloc] initWithFrame:CGRectMake(15, 15, 100, 100)];
    _goodsImageView.contentMode = UIViewContentModeScaleAspectFill;
    _goodsImageView.clipsToBounds = YES;
    [_goodsImageView sd_setImageWithURL:[NSURL URLWithString:_goods.teamIcon] placeholderImage:IMAGE_NAMED(@"noImage")];
    [self.contentView addSubview:_goodsImageView];
    
    _goodsImageView.userInteractionEnabled = YES;
    [_goodsImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewDidClick:)]];
    
    KNPhotoItems *items = [[KNPhotoItems alloc] init];
    items.sourceView = _goodsImageView;
    [self.itemsArr addObject:items];
        
    // 标题
    UILabel *titleLb = [[UILabel alloc] initWithFrame:CGRectMake(_goodsImageView.zx_right+10, 15, KScreenHeight/2, 30)];
    titleLb.textColor = CNavLightBlackColor;
    titleLb.font = DYFont(18);
    titleLb.text = @"标题";
    self.titleLb = titleLb;
    [self.contentView addSubview: titleLb];
    
    // 价格
    UILabel *price = [[UILabel alloc] initWithFrame:CGRectMake(_goodsImageView.zx_right+10, titleLb.zx_bottom, KScreenHeight/2, 30)];
    price.textColor = [UIColor redColor];
    price.font = DYFont(18);
    price.text = @"￥0.00";
    self.spec_price = price;
    [self.contentView addSubview:price];
    
    [price mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLb.mas_bottom);
        make.left.equalTo(_goodsImageView.mas_right).offset(10);
    }];
    
    // 原始价格
    UILabel *org_price = [[UILabel alloc] initWithFrame:CGRectMake(price.zx_right+10, titleLb.zx_bottom, KScreenHeight/2, 30)];
    org_price.textColor = CNavDargGrayColor;
    org_price.font = DYFont(16);
    org_price.text = @"￥0.00";
    self.org_priceLb = org_price;
    [self.contentView addSubview:org_price];
    
    [org_price mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLb.mas_bottom);
        make.left.equalTo(price.mas_right).offset(5);
    }];

    // 选择描述
    CGFloat specWd = KScreenWidth - 15 - 10 - 100 - 10;
    UILabel *sepelab = [[UILabel alloc] initWithFrame:CGRectMake(_goodsImageView.zx_right+10, price.zx_bottom, specWd, 50)];
    sepelab.font = DYFont(15);
    self.specLab = sepelab;
    sepelab.numberOfLines = 2;
    [self.contentView addSubview:sepelab];
    
    NSString *str = @"";
    for (SepecModel *mo in _dataArr) {
        str = [NSString stringWithFormat:@"%@ %@",str,mo.name_sepec];
    }
    sepelab.text = [NSString stringWithFormat:@"请选择：%@", str];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:IMAGE_NAMED(@"good_pop_close") forState:UIControlStateNormal];
    btn.frame = CGRectMake(KScreenWidth - 55, 5, 50, 40);
    [btn addTarget:self action:@selector(hiddenView) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:btn];
}

- (void)setGoods:(HETeamModel *)goods {
    _goods = goods;
    _titleLb.text = goods.teamName;
    
    [self resetHead];
}

- (void)resetHead {
    [self refresshHeadInfoWithImages:_goods.teamIcon price:@"" orgPrice: @""];
}

- (void)refreshByselectItem:(compareSepecModel *)model {
    self.titleLb.text = model.matchStr;
    [self refresshHeadInfoWithImages:model.spec_pic price: model.spec_price orgPrice: model.org_price];
}

- (void)refresshHeadInfoWithImages:(NSString *)urls price:(NSString *)price orgPrice:(NSString *)orgPrice{
    [_goodsImageView sd_setImageWithURL:[NSURL URLWithString:urls] placeholderImage:IMAGE_NAMED(@"noImage")];
    
    if ([DYTools isBlankString:price]) {
        _spec_price.text = @"";
        _org_priceLb.text = @"";
    }else {
        _spec_price.text = [NSString stringWithFormat:@"￥%@", [NSDecimalNumber rounding:price afterPoint:2]];
        
        if (orgPrice) {
            NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
            NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString: [NSString stringWithFormat:@"￥%@", [NSDecimalNumber rounding:orgPrice afterPoint:2]] attributes:attribtDic];
            _org_priceLb.attributedText = attribtStr;
        }else {
            _org_priceLb.text = @"";
        }
    }
    [_collectionView reloadData];
}
 

#pragma mark - UICollectionView基础属性设置
- (void)setupConfig{
    _num = 1;
    _config = [[SepecConfig alloc]init];
    
    _config.height = KScreenHeight / 2.0  + 150;
    _config.bottomBarHeight = 50 + ([[UIApplication sharedApplication] statusBarFrame].size.height > 20 ? 34 : 0);
    _config.topHeadHeight = 130;
    _config.contentInsets = UIEdgeInsetsMake(10, 10, 10, 10);
   _config.sepecInsets = UIEdgeInsetsMake(5, 5, 5, 5);
    _config.sepecBorderWidth = 1;
    _config.sepeccornerRadius = 5;
    _config.sepecBackgroundColor = KHexColor(@"F8F8F8");
    _config.sepecSelectedBackgroundColor = CNavBgColor;
    _config.sepecSelectedBorderColor = [UIColor redColor];
    _config.sepecBorderColor = [UIColor darkGrayColor];
    _config.sepecFont = DYFont(15);
    _config.sepecSelectedFont = DYFont(15);
    _config.sepecTextColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1.0];
    _config.sepecSelectedTextColor = KWhiteColor;
    
    _config.sepecHeight = 28;
    _config.mininumsepecWidth = 0;
    _config.maximumsepecWidth = CGFLOAT_MAX;
    _config.lineSpacing = 10;
    _config.interitemSpacing = 15;
    
    _comfireBtnTitle = @"立即购买";
    _enableCancle = YES;
}

#pragma mark - collectionView
- (void)addInitCollectView{

    //1.初始化layout
//     UICollectionViewFlowLayout*layout = [[UICollectionViewFlowLayout alloc] init];
//    layout.minimumInteritemSpacing = 5;
//    layout.minimumLineSpacing = 5;
//    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
//    layout.itemSize = CGSizeMake(KScreenWidth/5, 40);
//    //设置collectionView滚动方向
//    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    
   UICollectionViewLeftAlignedLayout *layout = [[UICollectionViewLeftAlignedLayout alloc]init];
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
//        layout.minimumLineSpacing = 10*WidthRatio;
        layout.minimumInteritemSpacing = 10;
        layout.sectionInset = UIEdgeInsetsMake(0, 15, 10, 15);
    

    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, AUTOY(_config.topHeadHeight), KScreenWidth, _contentView.zx_height - AUTOY(_config.topHeadHeight) - AUTOY(_config.bottomBarHeight)) collectionViewLayout:layout];
    [self.collectionView registerClass:[HESepecCell class] forCellWithReuseIdentifier:HESepceCellID];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HEHeaderViewID];
     [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:HEFooterViewID];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    _collectionView.allowsSelection = YES;
    [self.contentView addSubview:self.collectionView];
}

- (void)toDetailPage {
    if ([_delegate respondsToSelector:@selector(seeDetailsVC)]) {
        [_delegate seeDetailsVC];
    }
}

#pragma mark - 确定规格选择---根据项目需要返回指定数据
- (void)btnAction:(UIButton *)sender{
  
    if (self.selectModel == NULL) {
        [Dialog toastBottom:@"请选择您需要的服务"];
        return;
    }
    
    if (self.finishSelectedBlock) {
        self.finishSelectedBlock(self.selectModel);
    }
    
    [self hiddenView];
}

// 返回格子有多少组
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.dataArr.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    SepecModel *sepecModel = _dataArr[section];
    return sepecModel.arr_sepec.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HESepecCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:HESepceCellID forIndexPath:indexPath];
     
    SepecModel *model = _dataArr[indexPath.section];
    SepecDetailModel *sepecModel = model.arr_sepec[indexPath.row];
    cell.sepceModel = sepecModel;
    cell.sepeclabel.text = sepecModel.name_sepec;
    cell.layer.cornerRadius = self.config.sepeccornerRadius;
    cell.layer.masksToBounds = self.config.sepeccornerRadius > 0;
//    cell.contentInsets = self.config.sepecInsets;
    [self setCell:cell selected:sepecModel.selected];
    
    return cell;
}

- (void)setCell:(HESepecCell *)cell selected:(BOOL)selected {
    if (selected) {
        cell.sepeclabel.font = self.config.sepecSelectedFont;
        cell.sepeclabel.textColor = self.config.sepecSelectedTextColor;
        cell.contentView.backgroundColor = self.config.sepecSelectedBackgroundColor;
    }else {
        cell.sepeclabel.font = self.config.sepecFont;
        cell.sepeclabel.textColor = self.config.sepecTextColor;
        cell.contentView.backgroundColor = self.config.sepecBackgroundColor;
    }
}

////头部视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *headerView = nil;
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
      
        headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HEHeaderViewID forIndexPath:indexPath];
        SepecModel *model = _dataArr[indexPath.section];
        [headerView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];//每次刷新 移除子视图 不然会重叠
        
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(5, 0, KScreenWidth - 10, 0.5)];
        line.backgroundColor = CSplitLineColor;
        [headerView addSubview:line];
        
        UILabel *sepecNamelab = [[UILabel alloc]initWithFrame:CGRectMake(14, 1, [model.name_sepec widthForFont:DYFont(15)] + 10, 40)];
        sepecNamelab.font = DYBlodFont(16);
        sepecNamelab.text = model.name_sepec;
        [headerView addSubview:sepecNamelab];
        
        if (indexPath.section == 0 && _showDetailBtn) {
            UILabel *seeDetailLb = [[UILabel alloc]initWithFrame:CGRectMake(sepecNamelab.zx_right, 1, [@"查看详请 >" widthForFont:DYFont(15)] + 10, 40)];
            seeDetailLb.font = DYFont(15);
            seeDetailLb.text = @"查看详请 >";
            seeDetailLb.textColor = CNavBgColor;
            seeDetailLb.userInteractionEnabled = YES;
            [headerView addSubview:seeDetailLb];
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toDetailPage)];
            [seeDetailLb addGestureRecognizer:tap];
        }
        
        return headerView;
    }
    else{
        if (_dataArr.count-1 == indexPath.section) {
           UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:HEFooterViewID forIndexPath:indexPath];
//            UIView *line = [[UIView alloc]initWithFrame:CGRectMake(5, 0, KScreenWidth - 10, 1)];
//            line.backgroundColor = CSplitLineColor;
//            [headerView addSubview:line];
//
//            UIView *countbgview = [[UIView alloc]initWithFrame:CGRectMake(0, 1, KScreenWidth, 49)];
//            countbgview.backgroundColor = [UIColor whiteColor];
//            [headerView addSubview:countbgview];
//
//            UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(15, 5, KScreenWidth/2, 39)];
//            lab.text = @"购买数量: ";
//            lab.textColor = [UIColor blackColor];
//            lab.font = DYFont(15);
//            [countbgview addSubview:lab];
//
//            CountView *view = [[CountView alloc]initWithFrame:CGRectMake(countbgview.zx_width - 155, 19/2, 140, 30)];
//            view.count = 1;
//            view.goodstock = 1000000;//可选择的最大销量
//            view.CountBlock = ^(NSInteger count){
//                self.num = count;
//            };
//            [countbgview addSubview:view];
            return headerView;
        }else{
            return nil;
        }
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(KScreenWidth, 41);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    if (_dataArr.count - 1 == section) {
         return CGSizeMake(KScreenWidth, 70);
    }
    return CGSizeMake(0, 0);
}


#pragma mark - ......::::::: UICollectionViewDelegate :::::::......
// 选中操作
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SepecModel *model = self.dataArr[indexPath.section];
    SepecDetailModel *sepecModel = model.arr_sepec[indexPath.item];
    
    // 重置所有选中项
    [self restAllAttrModel:sepecModel];
    
    // 标记选中项
    if (_enableCancle) {
        sepecModel.selected =  !sepecModel.selected;
    }else {
        sepecModel.selected = YES;
    }
    
    if (sepecModel.selected) {
        self.selectModel = sepecModel;
        
        self.specLab.text  = [NSString stringWithFormat:@"已选择：%@ - %@", _goods.teamName, sepecModel.name_sepec];

        // 改变头部信息
        if (indexPath.section == 0) {
            for (compareSepecModel *compareModel in _comparedataArr) {
                if (compareModel.goodspriceid == [sepecModel.id_sepec integerValue]) {
                    [self refreshByselectItem:compareModel];
                    break;
                }
            }
        }else {
            compareSepecModel *matchComp = NULL;
            for (compareSepecModel *compareModel in _comparedataArr) {
                if (compareModel.goodspriceid == [sepecModel.id_sepec integerValue]) {
                    matchComp = compareModel;
                    break;
                }
            }
            compareSepecModel *compareModel = [compareSepecModel new];
            compareModel.spec_price = matchComp.spec_price;
            compareModel.spec_pic = _goods.teamIcon;
            [self refreshByselectItem:matchComp];
            
            self.specLab.text  = [NSString stringWithFormat:@"简介：%@", sepecModel.desc];

        }
    }else {
        self.selectModel = NULL;
        self.specLab.text  = @"请选择您需要的服务";
        [self resetHead];
    }
  
    [collectionView reloadData];
}

- (void)restAllAttrModel:(SepecDetailModel *)subModel {
    for (SepecModel *model in _dataArr) {
        for (SepecDetailModel *demodel in model.arr_sepec) {
            if (subModel != demodel) {
                demodel.selected = NO;
            }
        }
    }
}


#pragma mark - ......::::::: UICollectionViewDelegateFlowLayout :::::::......

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout*)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    SepecModel *model = self.dataArr[indexPath.section];
    SepecDetailModel *sepecModle = model.arr_sepec[indexPath.row];
    CGFloat width = sepecModle.contentSize.width + self.config.sepecInsets.left + self.config.sepecInsets.right;
    if (width < self.config.mininumsepecWidth) {
        width = self.config.mininumsepecWidth;
    }
    if (width > self.config.maximumsepecWidth) {
        width = self.config.maximumsepecWidth;
    }
    
    return CGSizeMake(width, self.config.sepecHeight);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return self.config.interitemSpacing;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return self.config.lineSpacing;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return self.config.contentInsets;
}


#pragma mark -
- (void)imageViewDidClick:(UITapGestureRecognizer *)tap{
    KNPhotoBrowser *photoBrowser = [[KNPhotoBrowser alloc] init];
    photoBrowser.itemsArr = [self.itemsArr copy];
//    photoBrowser.isNeedPageControl = true; // if it has video to play , I do not suggest you to use PageControl
    photoBrowser.isNeedPageNumView = true;
    photoBrowser.isNeedRightTopBtn = true;
    photoBrowser.isNeedPictureLongPress = true;
    photoBrowser.isNeedPanGesture = true;
    photoBrowser.isNeedPrefetch = true;
    photoBrowser.isNeedAutoPlay = true;
    
    photoBrowser.currentIndex = 0;
    photoBrowser.delegate = self;
    [photoBrowser present];
    
    _photoBrowser = photoBrowser;
}

- (NSMutableArray *)itemsArr{
    if (!_itemsArr) {
        _itemsArr = [NSMutableArray array];
    }
    return _itemsArr;
}



#pragma mark - delegate

/* photoBrowser 右上角按钮的点击 */
- (void)photoBrowserRightOperationAction{
   
   __weak typeof(self) weakself = self;
   KNActionSheet *actionSheet = [[KNActionSheet share] initWithTitle:@"" cancelTitle:@"" titleArray:@[@"保存"].mutableCopy destructiveArray:@[@"0"].mutableCopy actionSheetBlock:^(NSInteger buttonIndex) {
       if (buttonIndex == 0) {

           [weakself toSaveImage:[NSURL URLWithString:weakself.photoBrowser.itemsArr[weakself.photoBrowser.currentIndex].url]];
       }
   }];
   
   [actionSheet show];
}

/// long press
/// @param photoBrowser pb
/// @param longPress press
- (void)photoBrowser:(KNPhotoBrowser *)photoBrowser longPress:(UILongPressGestureRecognizer *)longPress {
   if (longPress.state == UIGestureRecognizerStateBegan) {
       [photoBrowser setImmediatelyPlayerRate:2];
   }else if (longPress.state == UIGestureRecognizerStateEnded || longPress.state == UIGestureRecognizerStateCancelled || longPress.state == UIGestureRecognizerStateFailed || longPress.state == UIGestureRecognizerStateRecognized){
       [photoBrowser setImmediatelyPlayerRate:1];
   }
}


- (void)toSaveImage:(NSURL *)url {
   SDWebImageManager *manager = [SDWebImageManager sharedManager];
   if ([manager cacheKeyForURL:url]) {
      [[manager imageCache] queryImageForKey:url.absoluteString options:SDWebImageFromCacheOnly context:nil completion:^(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType) {
          // 保存图片到相册中
          UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
       }];
       return;
   }
   else {
       //从网络下载图片
       NSData *data = [NSData dataWithContentsOfURL:url];
       UIImage *img = [UIImage imageWithData:data];
       // 保存图片到相册中
       UIImageWriteToSavedPhotosAlbum(img,self, @selector(image:didFinishSavingWithError:contextInfo:),nil);
   }
}

//保存图片完成之后的回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
 contextInfo:(void *)contextInfo {
   if (error != NULL) {
       [Dialog toast:@"图片保存失败" delay:2.0];
   }
   else  // No errors
   {
       [Dialog toast:@"图片保存成功" delay:2.0];
   }
}

@end
